import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class Counter extends Component {
    constructor(props) {
        super(props);
        this.state = { num: props.n }
    }
    handleClick = () => {
        // react 批量处理状态的 react能监控到 就批量处理
        this.setState(prevState => {
            return { num: prevState.num + 1 };
        });
        this.setState(prevState => {
            return { num: prevState.num + 1 };
        });
        this.setState(prevState => {
            return { num: prevState.num + 1 };
        });
    }
    render() { 
        return ( <div>
            {this.state.num}
            <br/>
            <button onClick = {this.handleClick}>click me</button>
        </div> );
    }
}

ReactDOM.render(<Counter n = {100}></Counter>, window.root)
 
export default Counter;

let isBatching = true; // 默认是批处理
class Component {
    constructor() {
        this.state = {n: 1};
        this.pendingState = {...this.state}
    }
    setState(obj) {
        if (isBatching) {
            this.pendingState = {...this.pendingState, ...obj}
        } else {
            this.state = {...this.state, ...obj}
            this.render();
        }
    }
    transaction() {
        this.state = this.pendingState;
        this.render();
        isBatching = false
    }
}
class My extends Component {
    constructor() {
        super()
    }
    update() {
        this.setState({ n: this.state.n + 1 });
        this.setState({ n: this.state.n + 1 });
        this.setState({ n: this.state.n + 1 });
        this.transaction();
    }
    render() {
        console.log(this.state.n)
    }
}